import {Form, Drawer, Row, Col, Input, InputNumber, Space, Button, Divider, Select, DatePicker} from 'antd';
import {useEffect, useState} from 'react';
import {connect} from 'umi';
import {normFile, uuid} from "@/utils/upload";
import 'braft-editor/dist/index.css';
import AliyunOSSUpload from '@/components/AliyunOSSUpload/App';
import locale from "antd/es/date-picker/locale/zh_CN";
import dayjs from "dayjs";

const {RangePicker} = DatePicker;

const DataForm = (props) => {
  const {dispatch, submitting, goodsList, serveList, pkgList,} = props;
  const {dataForm, setDataForm, tablePayload, setTablePayload} = props.data;
  const [form] = Form.useForm();
  const [cover, setCover] = useState([]);
  const [content, setContent] = useState([]);
  const [aboutType, setAboutType] = useState(0);

  useEffect(() => {
    dispatch({type: 'MallCommon/fetchPkgList'});
    dispatch({type: 'MallCommon/fetchServeList'});
    dispatch({type: 'MallCommon/fetchGoodsList'});
  }, [dispatch]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({aboutType: 0, status: 1, orderby: 0});
    }

    if (dataForm && dataForm.data) {
      let cover_ = [];
      if (dataForm.data.cover) {
        cover_ = [{uuid: uuid(), name: dataForm.data.cover.split("/").pop(), status: 'done', url: dataForm.data.cover}];
      }
      setCover(cover_)

      let content_ = [];
      if (dataForm.data.content) {
        content_ = JSON.parse(dataForm.data.content).map(d => {
          return {uuid: uuid(), name: d.split("/").pop(), status: 'done', url: d}
        });
      }
      setContent(content_);

      form.setFieldsValue({
        ...dataForm.data,
        time: dataForm.data.timeStart ? [dayjs(dataForm.data.timeStart, 'YYYY-MM-DD'), dayjs(dataForm.data.timeEnd, 'YYYY-MM-DD')] : [],
        content: content_,
        cover: cover_
      });

      if (dataForm.data.aboutType === 0) {
        dispatch({type: 'MallCommon/fetchGoodsSpecList', payload: {goodsId: dataForm.data.aboutId}});
      }
      if (dataForm.data.aboutType === 1) {
        dispatch({type: 'MallCommon/fetchServeCardList', payload: {serveId: dataForm.data.aboutId}});
      }

      setAboutType(dataForm.data.aboutType);
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      if (values.content && (values.content.length > 0)) {
        values.content = JSON.stringify(values.content.filter(d => d.status === 'done').map(d => d.url));
      } else {
        values.content = '[]';
      }

      if (values.cover && (values.cover.length > 0)) {
        values.cover = values.cover.filter(d => d.status === 'done').pop().url;
      } else {
        values.cover = '';
      }

      if (values.time) {
        values.timeStart = dayjs(values.time[0]).format('YYYY-MM-DD') + ' 00:00:00';
        values.timeEnd = dayjs(values.time[1]).format('YYYY-MM-DD') + ' 23:59:59';
      }

      dispatch({
        type: values.id ? 'POperationCampain/edit' : 'POperationCampain/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    form.resetFields();
    setContent([]);
    setCover([]);
    setAboutType(0);
  }

  return (
    <Drawer
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onClose={onCancel}
      forceRender={true}
      width={940}
      headerStyle={{padding: '8px 24px'}}
      bodyStyle={{paddingBottom: 80}}
      extra={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button loading={submitting} onClick={onOk} type="primary">提交</Button>
        </Space>
      }
    >
      <Form layout='horizontal' labelCol={{span: 6}} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='aboutType' label='关联类型'
              rules={[
                {required: true, message: '关联类型不能为空'},
              ]}
            >
              <Select placeholder='请选择关联类型' onSelect={e => setAboutType(e)}>
                <Select.Option value={0}>商品</Select.Option>
                <Select.Option value={1}>服务</Select.Option>
                <Select.Option value={2}>套餐</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='pubState' label='推广类型'
              rules={[
                {required: true, message: '推广类型不能为空'},
              ]}
            >
              <Select placeholder='请选择推广类型'>
                <Select.Option value={1}>通用推广</Select.Option>
                <Select.Option value={0}>渠道推广</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          {(aboutType === 0) && (
            <>
              <Col span={24}>
                <Form.Item
                  labelCol={{span: 3}}
                  name='aboutId' label='商品名称'
                  rules={[
                    {required: true, message: '商品名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择商品名称' options={goodsList} allowClear showSearch
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </>
          )}
          {(aboutType === 1) && (
            <>
              <Col span={24}>
                <Form.Item
                  labelCol={{span: 3}}
                  name='aboutId' label='服务名称'
                  rules={[
                    {required: true, message: '服务名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择服务名称' options={serveList} allowClear showSearch
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </>
          )}
          {(aboutType === 2) && (
            <>
              <Col span={24}>
                <Form.Item
                  labelCol={{span: 3}}
                  name='aboutId' label='套餐名称'
                  rules={[
                    {required: true, message: '套餐名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择套餐名称' options={pkgList} allowClear showSearch
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </>
          )}
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{span: 3}}
              name='name' label='活动名称'
              rules={[
                {required: true, message: '活动名称不能为空'},
              ]}>
              <Input placeholder='请输入活动名称'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='time' label='活动时间'
              rules={[
                {required: true, message: '活动时间不能为空'},
              ]}>
              <RangePicker locale={locale} style={{width: '100%'}} format={'YYYY-MM-DD'}/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='url' label='跳转链接'
              rules={[
                {required: true, message: '跳转链接不能为空'},
              ]}>
              <Input placeholder='请输入跳转链接'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='status' label='当前状态'
              rules={[
                {required: true, message: '当前状态不能为空'},
              ]}
            >
              <Select placeholder='请选择当前状态'>
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='orderby' label='排序属性'
              rules={[
                {required: true, message: '排序属性不能为空'},
              ]}>
              <InputNumber style={{width: '100%'}} placeholder='请输入排序属性'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='description' label='活动描述'
              rules={[
                {required: true, message: '活动描述不能为空'},
              ]}
            >
              <Input.TextArea placeholder='请输入活动描述'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='remark' label='备注信息'
              rules={[
                {required: false, message: '备注信息不能为空'},
              ]}
            >
              <Input.TextArea placeholder='请输入备注信息'/>
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{marginTop: 0}}/>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{span: 3}}
              name={'cover'}
              label="封面图"
              tooltip="宽高800*800px，大小5M内"
              rules={[
                {required: true, message: '封面图不能为空'},
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{images: cover, setImages: setCover, size: 5, len: 1, accept: 'image/*'}}/>
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{marginTop: 0}}/>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{span: 3}} tooltip="宽750px，大小5M内"
              name={'content'}
              label="活动内容"
              rules={[
                {required: false, message: '活动内容不能为空'},
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{images: content, setImages: setContent, size: 5, len: 6, accept: 'image/*'}}/>
            </Form.Item>
          </Col>
        </Row>

      </Form>
    </Drawer>
  );
};


export default connect(({loading, MallCommon}) => {
  return {
    submitting: loading.effects['POperationCampain/add'] || loading.effects['POperationCampain/edit'],
    goodsList: MallCommon.goodsList,
    serveList: MallCommon.serveList,
    pkgList: MallCommon.pkgList,
  };
})(DataForm);

